package day21;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * DataStreamDemo.java
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description 操作基本数据的流对象，可以使用UTF-8修改版编码读写操作文件中的字符串
 * @since 1.0.0
 * @date 2013-6-30下午6:38:57
 *
 */
public class DataStreamDemo {

	public static void main(String[] args) {
		writeData();
		readData();
		writeUTFData();
		readUTFData();
	}
	
	public static void readUTFData() {
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(new FileInputStream("utf.txt"));
			String s = dis.readUTF();
			System.out.println("String=" +s);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != dis) {
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}	
	
	//注意：修改版的utf-8一个汉字占4个字节
	public static void writeUTFData() {
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(new FileOutputStream("utf.txt"));
			dos.writeUTF("你好呀！");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != dos) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void readData() {
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(new FileInputStream("data.txt"));
			int num = dis.readInt();
			System.out.println("int=" +num);
			boolean b = dis.readBoolean();
			System.out.println("boolean="+b);
			double dou = dis.readDouble();
			System.out.println("double"+dou);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != dis) {
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public  static void writeData() {
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(new FileOutputStream("data.txt"));
			dos.writeInt(278);
			dos.writeBoolean(true);
			dos.writeDouble(2789.222);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != dos) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
 	}
}
